#include "SHT30.h"

HAL_StatusTypeDef SHT30_Init(SHT30_HandleTypeDef *sht30, I2C_HandleTypeDef *hi2c) {
    sht30->hi2c = hi2c;
    return HAL_OK;
}

HAL_StatusTypeDef SHT30_WriteCommand(SHT30_HandleTypeDef *sht30, uint16_t command) {
    uint8_t data[2];
    data[0] = (command >> 8) & 0xFF;
    data[1] = command & 0xFF;
    return HAL_I2C_Master_Transmit(sht30->hi2c, SHT30_I2C_ADDRESS, data, 2, HAL_MAX_DELAY);
}

HAL_StatusTypeDef SHT30_ReadData(SHT30_HandleTypeDef *sht30, uint8_t *data, uint8_t length) {
    return HAL_I2C_Master_Receive(sht30->hi2c, SHT30_I2C_ADDRESS, data, length, HAL_MAX_DELAY);
}

void SHT30_GetTempAndHumidity(SHT30_HandleTypeDef *sht30, float *temperature, float *humidity) {
    uint8_t data[6];
    SHT30_WriteCommand(sht30, 0x2C10); // 发送测量命令
    HAL_Delay(5); // 等待测量完成

    if (SHT30_ReadData(sht30, data, 6) == HAL_OK) {
        uint16_t rawTemperature = (data[0] << 8) | data[1];
        uint16_t rawHumidity = (data[3] << 8) | data[4];

        *temperature = -45.0f + 175.0f * (rawTemperature / 65535.0f);
        *humidity = 100.0f * (rawHumidity / 65535.0f);
    } else {
        *temperature = -999.0f;
        *humidity = -999.0f;
    }
}